package com.jinyijia.api.rest.v1;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${utils.picture.endpoint}")
    private String END_POINT;
    @Value("${utils.picture.accessKeyId}")
    private String ACCESS_KEY_ID;
    @Value("${utils.picture.accessKeySecret}")
    private String ACCESS_KEY_SECRET;
    @Value("${utils.picture.bucketName}")
    private String BUCKET_NAME;

    private String imgUrl = "http://image-jinyijia1688-com.oss-cn-beijing.aliyuncs.com/";

    @PostMapping()
    public JSONObject upload(@RequestParam("file") MultipartFile file) {
        JSONObject result = new JSONObject();
        try {
            byte[] bytes = file.getBytes();
            String fileMd5 = DigestUtils.md5DigestAsHex(bytes);
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            String fileUrl = "goods_" + fileMd5 + suffix;
            if (uploadPic(file, fileUrl)) {
                result.put("error", 0);
                result.put("url", imgUrl + fileUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("error", 1);
            result.put("message", e.getMessage());
        }
        return result;

    }

    /**
     * 上传图片
     *
     * @param file
     * @param name
     * @return
     */
    public Boolean uploadPic(MultipartFile file, String name) {
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            ossClient.putObject(BUCKET_NAME, name, file.getInputStream());
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return false;
    }

}
